package com.wngbms.multidatasource.datasource.mybatis.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class ThreadLocalPagePlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
/*        StatementHandler handler = (StatementHandler) invocation.getTarget();

        MetaObject metaObject = MetaObject.forObject(handler,
                SystemMetaObject.DEFAULT_OBJECT_FACTORY,
                SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
                new DefaultReflectorFactory());

        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        String statementId = mappedStatement.getId();

        if (statementId.endsWith("ByPage")) {
            BoundSql boundSql = handler.getBoundSql();
            String sql = boundSql.getSql();

            String countSql = "select count(*) " + sql.substring(sql.indexOf("from"));

            Connection connection = (Connection) invocation.getArgs()[0];
            PreparedStatement ps = connection.prepareStatement(countSql);

            ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
            parameterHandler.setParameters(ps);

            ResultSet resultSet = ps.executeQuery();
            if (resultSet.next()) {
                int total = resultSet.getInt(1);
            }

            String pageSql = sql + " limit " + 0 + " , " + 10;
            metaObject.setValue("delegate.boundSql.sql", pageSql);
        }*/

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
